#include "spheresurface.h"
#include <algorithm>

// =================================================================================================
// This tests for t intersection
// =================================================================================================
float SphereSurface::SurfaceIntersection(const Ray& ray) {
    // -- constant coefficients for a quadratic equation
    float a, b, c;
    const Vector4& raydir = ray.direction;
    const Vector4& rayorigin = ray.direction;
    const Vector4& sphereor = sphere.center;
    float sphererad = sphere.radius;
    float difforiginx = rayorigin.x - sphereor.x;
    float difforiginy = rayorigin.y - sphereor.y;
    float difforiginz = rayorigin.z - sphereor.z;

    a = (raydir.x * raydir.x) + (raydir.y * raydir.y) + (raydir.z * raydir.z);
    b = 2 * ((raydir.x * (rayorigin.x - sphereor.x)) + (raydir.y * (rayorigin.y - sphereor.y))
           + (raydir.z * (rayorigin.z - sphereor.z)));
    c = (difforiginx * difforiginx) + (difforiginy * difforiginy) + (difforiginz * difforiginz) 
        - (sphererad * sphererad);

    float discriminant = ((b * b) - (4 *(a * c)));
    
    if(discriminant < 0.001f)
        return 0.0f;

    float denom = 2 * (a * c);
    float newb = (-b)/denom;
    float newdis = sqrt(discriminant)/denom;

    float t = std::min(newb + newdis, newb - newdis);

    if(t < 0.0001f)
        return 0.0f;

    return t;
}